import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ValidationPipe, Logger } from '@nestjs/common';
import { TransformInterceptor } from './common/interceptors/transform.interceptor';
import {
  HttpExceptionFilter,
  AllExceptionsFilter,
} from './common/filters/http-exception.filter';
import { ConfigService } from '@nestjs/config';
import { logger } from './common/logger/logger.config';
async function bootstrap() {
  // 使用自定义日志记录器创建应用
  const app = await NestFactory.create(AppModule, {
    logger,
  });

  // 启用CORS
  app.enableCors();

  // 全局前缀
  app.setGlobalPrefix('api');

  // 全局验证管道
  app.useGlobalPipes(
    new ValidationPipe({
      whitelist: true, // 过滤掉未在DTO中声明的属性
      transform: true, // 自动转换类型
      forbidNonWhitelisted: true, // 禁止未在DTO中声明的属性
      transformOptions: {
        enableImplicitConversion: true, // 启用隐式类型转换
      },
    }),
  );

  // 全局响应拦截器
  app.useGlobalInterceptors(new TransformInterceptor());

  // 全局异常过滤器
  const httpExceptionFilter = app.get(HttpExceptionFilter);
  const allExceptionsFilter = app.get(AllExceptionsFilter);
  app.useGlobalFilters(httpExceptionFilter, allExceptionsFilter);

  // 获取配置服务
  const configService = app.get(ConfigService);
  const port = configService.get<number>('PORT', 3000);

  await app.listen(port);
  Logger.log(`应用已启动: http://localhost:${port}/api`, 'Bootstrap');
}

// eslint-disable-next-line @typescript-eslint/no-floating-promises
bootstrap();
